package exttable.formgenerator;

import dbutils.DbUtils;
import exttable.SGTTestParametrs;
import exttable.dbclasses.Answer;
import exttable.dbclasses.Probationer;
import exttable.dbclasses.Question;
import exttable.threads.ThreadFactory;
import utils.Localisation;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ADMIN
 * Date: 29.06.2010
 * Time: 14:41:36
 * To change this template use File | Settings | File Templates.
 */
public class ListenerFactory {
    public static ActionListener getFormGenerator(final Object obj) {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                Component comp = (Component) e.getSource();
                if (obj == null) {
                    new FormGenerator(comp.getName(), obj);
                }
            }
        };
    }

    public static ActionListener getViewGenerator() {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JMenuItem menuItem = (JMenuItem) e.getSource();
                new ViewGenerator(menuItem.getName());

            }
        };
    }

    public static ActionListener recordToDB(final String tableName, final Vector<String> nameOfColumnForInsert, final Vector<Object> valueOfColumnForInsert, final JFrame frame, final int insertBySystem, final Object obj) {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (obj == null) {
                    StaticMethods.insertValuesToDB(tableName, nameOfColumnForInsert, valueOfColumnForInsert, frame, insertBySystem);
                } else {
                    StaticMethods.updateRowInDB(tableName, nameOfColumnForInsert, valueOfColumnForInsert, frame, insertBySystem, obj);
                }

            }
        };

    }

    public static FocusListener checkFormL() {
        return new FocusListener() {
            public void focusGained(FocusEvent e) {

            }

            public void focusLost(FocusEvent e) {
                Component comp = (Component) e.getSource();
//                System.out.println(comp.getClass());
                if (comp.getClass().getSimpleName().equals("JTextField")) {
                    JTextField field = (JTextField) comp;
                    if (field.getText().trim().length() > 0 & !field.getName().equals("volunteer_code")) {
                        field.setBackground(Color.white);
                        field.transferFocusDownCycle();
                    } else {
//                        field.setBackground(Color.red);
//                     comp.requestFocus();
                        field.transferFocusBackward();
                    }
                }

            }

        };
    }

    public static ActionListener getFrameCalendar(final JFormattedTextField dataField) {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JFrame f = new JFrame("Calendar");

                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                Container c = f.getContentPane();
                c.setLayout(new FlowLayout());
                c.add(new JTCalendarRu(dataField, f));
                f.pack();
                f.setResizable(false);
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        };
    }

    public static ActionListener generateViewAndInsertForm() {
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JComponent jc = (JComponent) e.getSource();
                String tableName = jc.getName();
                try {
                    new ViewDataBaseTableModel(tableName);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        };
    }

    public static ActionListener genenerateSelectGroupAndProbationer() {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                new SelectGroupAndProbationerForm();
            }
        };
    }

    public static ActionListener genenerateSelectPhaseAndProbationer(final String operation) {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                new SelectPhaseAndProbationerFormForQuestionnaire(operation);
            }
        };
    }

    public static ActionListener downloadQuestionnaireResults() {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
//                    new QuestionnaireAnalyser();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        };
    }


    public static ActionListener reloadProbationerList() {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox jcb = (JComboBox) e.getSource();
                SelectPhaseAndProbationerFormForQuestionnaire.changeDFCBModel(jcb);
            }
        };
    }

    public static ActionListener reloadVisitList() {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox jcb = (JComboBox) e.getSource();
                SelectPhaseAndProbationerFormForQuestionnaire.changeVisitDFCBModel(jcb);
            }
        };
    }

    public static ActionListener saveAnswers(final List<Question> questions, final Probationer probationer, final int visitId, final String operation) {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (MessageFactory.isToSave()) {
                    int countQuestion = 0;
                    List<Answer> ansList = new ArrayList<Answer>();
                    Map<Integer, Answer> mapQuestionsAnswers = new HashMap<Integer, Answer>();
                    for (Question q : questions) {

                        if (q.getSubQuestions().size() < 1) {
                            ansList.add((Answer) q.getAnswerBox().getSelectedItem());
                            countQuestion = countQuestion + 1;
                            mapQuestionsAnswers.put(countQuestion, (Answer) q.getAnswerBox().getSelectedItem());
                        } else {
                            for (Question subq : q.getSubQuestions()) {
                                ansList.add((Answer) subq.getAnswerBox().getSelectedItem());
                                countQuestion = countQuestion + 1;
                                mapQuestionsAnswers.put(countQuestion, (Answer) subq.getAnswerBox().getSelectedItem());
                            }

                        }
                    }
                    StaticMethods.saveValuesToResultAnswers(probationer, visitId, mapQuestionsAnswers, operation);
                    SelectPhaseAndProbationerFormForQuestionnaire.changeVisitDFCBModel(SelectPhaseAndProbationerFormForQuestionnaire.getProbationerBox());
                }


            }
        };
    }

    public static WindowListener closeFrame() {
        return new WindowListener() {

            @Override
            public void windowOpened(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowClosing(WindowEvent e) {
                Object[] options = {Localisation.getMessage("message.yes"), Localisation.getMessage("message.no")};
                int n = JOptionPane.showOptionDialog(e.getWindow(), Localisation.getMessage("message.exitMdt"),
                        Localisation.getMessage("message.title"), JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                if (n == 0) {
                    e.getWindow().setVisible(false);
                    try {
                        StaticMethods.changeInSystem(0, "", SGTTestParametrs.getInstance().getUserName());
                    } catch (SQLException e1) {
                        e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                    System.exit(0);

                }
            }

            @Override
            public void windowClosed(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowIconified(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowActivated(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }
        };
    }

    public static ActionListener RunQuestionnaireAnalyser() {
        return new ActionListener() {
            private JFileChooser fc;
            private String filePath;

            @Override
            public void actionPerformed(ActionEvent e) {
                fc = new JFileChooser();
                fc.setDialogTitle(Localisation.getMessage("form.selectplaceandname"));
                fc.showSaveDialog((Component) e.getSource());
                fc.getSelectedFile();
                filePath = fc.getSelectedFile().getAbsolutePath();
                Thread th = new Thread(ThreadFactory.runQuestionnaireAnalyser(filePath));
                if (filePath != null) {
                    th.start();
                }
            }

        };
    }

    public static ActionListener getFilterSelector() {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JMenuItem menuItem = (JMenuItem) e.getSource();
                new FilterSelector(menuItem.getName());

            }
        };
    }

    public static ActionListener getComboBoxSelector(final Object arrayItems[]) {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String tableName = ((Component) e.getSource()).getName();
                try {
                    new ComboBoxSelector(tableName, arrayItems);
                } catch (Exception e1) {
                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        };
    }

    public static ActionListener setProbationerCodeEqualsVolunteerCode() {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox jcb = (JComboBox) e.getSource();
                JPanel jp = (JPanel) jcb.getParent();
                for (Component res : jp.getComponents()) {
                    if (res.getClass().getSimpleName().equals("JTextField") & res.getName().equals("probationer_code")) {
                        JTextField jtf = (JTextField) res;
                        jtf.setText(jcb.getSelectedItem().toString());
                        break;
                    }
                }
            }
        };
    }

    public static ActionListener selectUnSelectAllInJList(final JList jList) {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource().getClass().getSimpleName().equals("JCheckBox")) {
                    JCheckBox jCheckBox = (JCheckBox) e.getSource();
                    if (jCheckBox.isSelected()) {
                        StaticMethods.selectAllIndicesInJList(jList);
                    } else {
                        jList.clearSelection();
                    }
                }

            }
        };
    }

    public static ActionListener selectUnSelectAllInJListWithSubJList(final JList mainJList, final JList ... subJListList) {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource().getClass().getSimpleName().equals("JCheckBox")) {
                    JCheckBox jCheckBox = (JCheckBox) e.getSource();
                    if (jCheckBox.isSelected()) {
                        StaticMethods.selectAllIndicesInJList(mainJList);
                    } else {
                        mainJList.clearSelection();
                        for (JList subJList:subJListList) {
                            subJList.setListData(new Array[]{});
                        }

                    }
                }

            }
        };
    }


}

